package com.superman.supermarket.client.composite.common.banner;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Image;
import com.superman.mvpframe.client.ajax.PostManAsyncCallBack;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.utils.StringUtils;
import com.superman.mvpframe.client.utils.XJsonUtil;
import com.superman.mvpframe.client.widget.zslider.ZSlider;
import com.superman.supermarket.client.event.PageJumpEvent;

/**
 * 广告位组件.基于Swiper,封装了数据请求
 * 
 * @author superman
 * @version 2018年7月16日下午10:21:40
 */
public class ADBanner extends ZSlider {

	protected void addItems(List<Map<String, Object>> list) {
		for (final Map<String, Object> map : list) {
			if (isImageValid(map)) {
				Image image = new Image();
				image.setUrl(String.valueOf(map.get("PIC_URL")));
				image.addClickHandler(new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						if (!StringUtils.isEmpty(String.valueOf(map.get("PIC_GOTO"))))
							// Window.Location.assign(String.valueOf(map.get("PIC_GOTO")));

							XGinjector.INSTANCE.getEventBus().fireEvent(new PageJumpEvent(String.valueOf(map.get("PIC_GOTO"))));
					}
				});
				this.addItem(image);
			}
		}
	}

	/**
	 * 根据广告位英文名获取广告位数据.
	 * 
	 * @author superman
	 * @version 2018年7月16日 下午10:53:27
	 * @param adEnName
	 */
	public void getADList(String adEnName) {
		// ajax获取广告位数据
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("EN_NAME", adEnName);
		XGinjector.INSTANCE.getPostMan().post("ad/list", map, new PostManAsyncCallBack() {

			@Override
			public void onBusinessError(String statusCode) {

			}

			@Override
			public void onBusinessOK(String response) {
				int count = XJsonUtil.getCount(response);
				if (count == 0)
					ADBanner.this.removeFromParent();
				else {
					addItems(XJsonUtil.getList(response));
					ADBanner.this.init();
				}
			}
		});

	}

	private boolean isImageValid(Map<String, Object> map) {
		boolean add = false;
		if (map.get("START_TIME") == null || map.get("END_TIME") == null)
			add = true;
		else {
			String startTime = (String) map.get("START_TIME");
			String endTime = (String) map.get("END_TIME");

			DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");

			Date startDate = dtf.parse(startTime);
			Date endDate = dtf.parse(endTime);

			Date nowDate = dtf.parse(dtf.format(new Date()));

			add = !nowDate.before(startDate) && !nowDate.after(endDate);
		}
		return add;
	}

}
